package com.maserb.monitor.service.base.impl;

import com.maserb.monitor.common.NetworkUtils;
import com.maserb.monitor.entity.*;
import com.maserb.monitor.repository.OprationLogRepository;
import com.maserb.monitor.service.author_manage.RoleService;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class ToolServiceImpl extends JpaSpecificationServiceImpl<OprationLogRepository, OprationLogRepository, OprationLog, String>
        implements IToolService {

    @Autowired
    private JwOrgService orgService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private OprationLogRepository repository;

    private Map<String, String> orgNameMap = new HashMap<String, String>();

    private Map<String, String> roleNameMap = new HashMap<String, String>();

    @PostConstruct
    @Override
    public void init() {
        List<JwOrgEntity> list = orgService.findAll();
        List<Role> roleList = roleService.findAll();
        for(JwOrgEntity dep : list) {
            orgNameMap.put(dep.getId(), dep.getName());
        }
        for(Role role : roleList) {
            roleNameMap.put(role.getId(), role.getRoleName());
        }
    }

    @Override
    public String formatYYMMDD(Date date) {
        if (date != null) {
            return formatDate("yyyy-MM-dd", date);
        }
        return "未知";
    }

    @Override
    public String formatYYMMDDHHMMSS(Date date) {
        if (date != null) {
            return formatDate("yyyy-MM-dd HH:mm:ss", date);
        }
        return "未知";
    }

    @Override
    public String formatHHMMSS(Date date) {
        if (date != null) {
            return formatDate("HH:mm:ss", date);
        }
        return "未知";
    }

    @Override
    public String formatYYMMDDHHMMSS(String date) {
        if(null!=date && !"".equals(date)){
            try {
                return date.substring(0,19);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return "";
    }

    @Override
    public String formatYYMMDD(String date) {
        if(null!=date && !"".equals(date)){
            try {
                return date.substring(0,10);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return "";
    }

    /**
    * @Description: 20180101010101转换为2018-01-01 01:01:01
    * @Param: [date]
    * @return: java.lang.String
    * @Author: Mr.Wang
    * @Date: 2018/8/8
    */
    @Override
    public String formatYYMMDDHHMMSSTime(String date) {
        if(null!=date && !"".equals(date)){
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                Date newDate = null;
                newDate = format.parse(date);
                SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = newFormat.format(newDate);
                return time;
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return "";
    }

    public Date parseDateFromNormalTimeFormat(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return format.parse(time);
        } catch (ParseException e) {
            log.error(e.getMessage());
        }

        return new Date();
    }

    @Override
    public void initCreateInfo(BaseEntity entity) {
        UserEntity user = (UserEntity) SecurityUtils.getSubject().getPrincipal();
        entity.setCreateBy(user.getUserName());
        entity.setCreateDate(new Date());
        entity.setCreateName(user.getRealName());
    }

    @Override
    public void initUpdateInfo(BaseEntity entity) {
        UserEntity user = (UserEntity) SecurityUtils.getSubject().getPrincipal();
        entity.setUpdateBy(user.getUserName());
        entity.setUpdateDate(new Date());
        entity.setUpdateName(user.getRealName());
    }

    @Override
    public Date parseDateFromNormalDateFormat(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return format.parse(time);
        } catch (ParseException e) {
            log.error(e.getMessage());
        }

        return new Date();
    }

    @Override
    public String parseStringFromNormalDateFormat(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String timeDate = "";
        try {
            Date date = format.parse(time);
            SimpleDateFormat formatyy = new SimpleDateFormat("yyyyMMddHHmmss");
            timeDate = formatyy.format(date);
        } catch (ParseException e) {
            log.error(e.getMessage());
        }
        return timeDate;
    }

    public String convertBooleanToStringYn(Boolean b) {
        if (b != null && b) {
            return "Y";
        }

        return "N";
    }

    public void saveOptLog(HttpServletRequest request, String opt, String remarks) {
        OprationLog log = new OprationLog();
        String ip = "";
        try {
            ip = NetworkUtils.getIpAddress(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.setIp(ip);
        log.setOptDate(new Date());
        log.setOpt(opt);
        log.setRemarks(remarks);

        UserEntity user = (UserEntity) SecurityUtils.getSubject().getPrincipal();
        if(user != null) {
            log.setUserName(user.getUserName());
            log.setUserId(user.getId());
        }

        saveOptLog(log);
    }

    public void saveOptLog(String ip, String opt, String remarks) {
        OprationLog log = new OprationLog();
        log.setIp(ip);
        log.setOpt(opt);
        log.setOptDate(new Date());
        log.setRemarks(remarks);

        saveOptLog(log);
    }

    public void saveOptLog(OprationLog log) {
        repository.save(log);
    }

    public String formatDate(String format, Date date) {
        SimpleDateFormat sf = new SimpleDateFormat(format);
        return sf.format(date);
    }

    /**
     * 获取部门名称
     * @param orgId 部门id
     * @return 部门名称
     */
    public String getOrgName(String orgId) {
        if(orgNameMap.containsKey(orgId)) {
            return orgNameMap.get(orgId);
        }
        return "未知";
    }

    /**
     * 获取角色名称
     * @param roleId 角色id
     * @return 角色名称
     */
    public String getRoleName(String roleId) {
        if(roleNameMap.containsKey(roleId)) {
            return roleNameMap.get(roleId);
        }
        return "未知";
    }

}